package com.star.view;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.alibaba.fastjson.JSON;
import com.star.model.NewsModel;
import com.star.model.UserModel;
import com.star.service.NewsService;
import com.star.service.UserService;
import com.star.utils.PageQuery;
import com.star.utils.StrUtils;

@Controller
public class IndexActionView extends MultiActionController {

	@Autowired
	private NewsService newsService;

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/loginSession.htm", method = RequestMethod.POST)
	public void loginSession(HttpServletRequest request, HttpServletResponse response) {
		String nick = request.getParameter("nick");
		if (StrUtils.isNotEmpty(nick)) {
			UserModel userModel = userService.selectUser(nick);
			if (userModel == null) {
				userModel = new UserModel();
				userModel.setUserName(nick);
				userModel.setFlag(1);// 1.QQ
				userService.insertUser(userModel);
				request.getSession().setAttribute("userModel", userService.selectUser(nick));
			} else {
				request.getSession().setAttribute("userModel", userModel);
			}
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("flag", "success");
			try {
				response.getWriter().write(JSON.toJSONString(model));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> model = new HashMap<String, Object>();
		String content = request.getParameter("content");
		String date = request.getParameter("params");
		String pageStar = request.getParameter("page");
		String search = request.getParameter("search");
		if (StrUtils.isEmpty(pageStar)) {
			pageStar = "0";
		}
		PageQuery pageQuery = new PageQuery(Integer.parseInt(pageStar), 10);
		List<NewsModel> newsList = newsService.querySearchPageQuery(date, search, pageQuery);
		if (StrUtils.isEmpty(content) || "all".equals(date)) {
			model.put("content", "全部");
		} else {
			model.put("content", content);
		}
		if (StrUtils.isNotEmpty(search)) {
			model.put("search", search);

		}
		model.put("newsList", newsList);
		model.put("size", newsList == null ? 0 : newsList.size());
		return new ModelAndView("/index", model);
	}

}
